<?php

namespace App\Services\User;

use App\Enums\ResponseCode;
use App\Enums\SmsEnum;
use App\Exceptions\BusinessException;
use App\Models\User;
use App\Services\AbstractBaseService;
use App\Services\Sms\SmsService;


class PasswordService extends AbstractBaseService
{

    /**
     * 修改登录密码。
     *
     * @param $userId
     * @param string $newPassword 新密码。
     * @return bool
     * @throws BusinessException
     */
    public static function editPassword($userId, string $newPassword)
    {

        $ok = User::where(['id'=>$userId])->update(['password'=> bcrypt($newPassword)]);
        if (!$ok) {
            self::exception(ResponseCode::SERVICE_UNAVAILABLE, trans('服务器繁忙,请稍候重试'));
        }
    }

    /**
     * 找回密码。
     *
     * @param string $account
     * @param string $mobile 验证码。
     * @param string $password 新密码。
     * @param int $verifyCode 验证码。
     * @return void
     * @throws BusinessException
     */
    public static function findPassword(string $mobile, string $password, int $verifyCode)
    {
        //用户的信息验证
        $user = User::query()->where(['mobile'=>$mobile])->first(['id']);
        if(empty($user)){
            self::exception(ResponseCode::VALIDATION_ERROR, trans('找回账号不存在请核对'));
        }
        //验证验证码
        SmsService::verify($mobile, $verifyCode, SmsEnum::FIND_PASSWORD);
        $ok = User::where(['id'=>$user->id])->update(['password'=> bcrypt($password)]);
        if (!$ok) {
            self::exception(ResponseCode::SERVICE_UNAVAILABLE, trans('服务器繁忙,请稍候重试'));
        }
    }

    /**
     * 手机号重置安全密码
     * @param int $userId 会员ID
     * @param string $verifyCode 验证码
     * @param string $newPayPwd 新的安全密码
     * @throws BusinessException
     */
    public static function editPayPass(int $userId,  string $newPayPwd, string $verifyCode)
    {
        $userInfo = User::query()->where(['id'=>$userId])->first(['id','mobile']);
        if(!$userInfo){
            self::exception(ResponseCode::SERVICE_UNAVAILABLE, trans('会员信息不存在'));
        }
        SmsService::verify($userInfo->mobile, $verifyCode, SmsEnum::EDIT_PAY_PASS);
        $ok = User::where(['id'=>$userInfo->id])->update(['pay_pass'=> bcrypt($newPayPwd)]);
        if (!$ok) {
            self::exception(ResponseCode::SERVICE_UNAVAILABLE, trans('服务器繁忙,请稍候重试'));
        }
    }

}
